﻿using System;
using System.Collections.Generic;
using Orchard.ContentManagement;
using Orchard.ContentManagement.MetaData;
using Orchard.ContentManagement.MetaData.Builders;
using Orchard.ContentManagement.MetaData.Models;
using Orchard.ContentManagement.ViewModels;
using System.Linq;

namespace Guang.UserGeolocation.Settings
{
    public class IpinfodbSetting
    {
        public string IpinfodbKey { get; set; }        
    }

    /// <summary>
    /// Overrides default editors to enable putting settings .
    /// </summary>
    public class IpinfodbSettingHooks : ContentDefinitionEditorEventsBase
    {
        /// <summary>
        /// Overrides editor shown when part is attached to content type. Enables adding setting field to the content part
        /// attached.
        /// </summary>
        /// <param name="definition"></param>
        /// <returns></returns>
        public override IEnumerable<TemplateViewModel> TypePartEditor(ContentTypePartDefinition definition)
        {
            if (definition.PartDefinition.Name != "UserCoordinatePart")
                yield break;
            var model = definition.Settings.GetModel<IpinfodbSetting>();
            
            yield return DefinitionTemplate(model);
        }

        public override IEnumerable<TemplateViewModel> TypePartEditorUpdate(ContentTypePartDefinitionBuilder builder, IUpdateModel updateModel)
        {
            if (builder.Name != "UserCoordinatePart")
                yield break;
            var model = new IpinfodbSetting();
            updateModel.TryUpdateModel(model, "IpinfodbSetting", null, null);
            builder.WithSetting("IpinfodbSetting.IpinfodbKey",model.IpinfodbKey);
            yield return DefinitionTemplate(model);
        }

    }
}

